import {formatTime} from "../../utils/util"
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import tool from "../../utils/tool";
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

const requests = require("../../utils/request")
const app = getApp()

var deliverOrderPage = 1
var appointOrderPage = 1

Page({


  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    appointOrderToShow:[],
    deliverOrderToShow:[],
    shoppingOrderToShow:[],
    showShare:false,
    shareOptions:[
      [
        {name:'社区',icon:'link'},
        { name: '微信', icon: 'wechat',openType:'share' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
      ],
    ],
    curShareOrderId:"",
    curShareOrderType:"",
    showDialog:false,
    curShareOrderObj:{},
    appointOrderIcon:'../../imgs/indexGrid/doorService.png',
    deliverOrderIcon:'../../imgs/deliverIcon.png'
  },
  onCloseDialog() {
    this.setData({ show: false });
  },
  onChangeTap(event) {
    // console.log(event)
    this.setData({
      active:event.detail.index
    })
    app.globalData.orderPageActive=event.detail.index
  },
  onshowShare(e)
  {
    // console.log(e.detail)
   let  showShare=e.detail.showShare
   let curShareOrderId=e.detail.curShareOrderId
   let curShareOrderType=e.detail.curShareOrderType
    this.setData({
      showShare,
      curShareOrderId,
      curShareOrderType
    })
    // console.log(this.data.curShareOrderId)
  },
  onShareClose() {
    this.setData({ showShare: false });
  },

  async onShareSelect(event) {
    // console.log("选择分享途径",event);
    const shareTarget = event.detail.name
    const curShareOrderId = this.data.curShareOrderId
    const curShareOrderType = this.data.curShareOrderType
    const deliverOrderToShow = this.data.deliverOrderToShow
    const appointOrderToShow = this.data.appointOrderToShow
    let curShareOrderObj=null
    if(shareTarget=="社区")
    {
      //添加订单动态
      switch(curShareOrderType)
      {
        case "deliverOrder":
          for(let item of deliverOrderToShow)
          {
            if(item.orderId==curShareOrderId)
            {
              curShareOrderObj=item
              break;
            }
          }
          break;
        case "appointOrder":
          for(let item of appointOrderToShow)
          {
            if(item.orderId==curShareOrderId)
            {
              curShareOrderObj=item
              break;
            }
          }
          break;
      }
      this.setData({
        showDialog:true,
        curShareOrderObj
      })
      // console.log('当前分享的订单内容',curShareOrderObj)
      const {senderAddress,totalWeight,orderTime,status,integration} = this.data.curShareOrderObj
      const curShareOrderObjJson = JSON.stringify(curShareOrderObj)
      const isOrderSharejson = JSON.stringify({
        'isOrderShare':true,
        'orderType':curShareOrderType
      })
      //还要发送网络请求，新增一条动态
      // `订单地址：${senderAddress};\n订单重量：${totalWeight};\n订单时间：${orderTime};\n订单状态：${status};\n获取积分:${integration}`,undefined,0,formatTime(new Date),`来自${app.globalData.userInfo.nickName}订单分享`
      let res = await requests.communityInterface(undefined,0,curShareOrderObjJson,isOrderSharejson,0,formatTime(new Date),`来自${app.globalData.userInfo.nickName}订单分享`,app.globalData.openid,"add")      
    }
    this.onShareClose();
  },



  async getDeliverorder()
  {
    // var res =  await requests.deliverorderInterface(null,null,null,null,null,null,null,null,app.globalData.openid,null,'getAll')
    var res = await requests.deliverOrderPageList(deliverOrderPage,app.globalData.openid)
    const deliverOrders = res.data.data.value.records
    // console.log(deliverOrders)
    let deliverOrderToShow = []
    for(let item of deliverOrders)
    {
      const usefulDeliverOrderInfo = {
        "orderId":item.orderId,
        "place":item.place,
        "status":item.orderStatus==0?"待处理":item.orderStatus==1?"已领取":item.orderStatus==2?"处理中":"已完成",
        "orderTime":item.time,
        "integration":item.integration,
        "totalWeight":item.weight+'kg',
        "addrNo":item.addrNo,
        "category":item.category
      }
      deliverOrderToShow.push(usefulDeliverOrderInfo)
    }
    
    return deliverOrderToShow
  },

  async getAllAppointOrder()
  {
    // let res = await requests.AppointOrderInterface(null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,app.globalData.openid,"getAll")
    let res = await requests.appointOrderPageList(appointOrderPage,app.globalData.openid)
    const appointOrders = res.data.data.value.records
    let appointOrderToShow = []
    for(let item of appointOrders)
    {
      const usefulOrderInfo = {
        "orderId":item.orderId,
        "senderAddress":item.senderAddress,
        "status":item.orderStatus==0?"待处理":item.orderStatus==1?"已领取":item.orderStatus==2?"处理中":"已完成",
        "orderTime":item.time,
        "integration":item.integration,
        "totalWeight":item.senderWeight+'kg',
        "items":item.items.replace(/goodsType/g,'类型').replace(/goodsWeight/g,'重量'),
        "senderDateBegin":item.senderDateBegin,
        "senderDateEnd":item.senderDateEnd,
        "senderRemark":item.senderRemark
      }
      // console.log(usefulOrderInfo)
      appointOrderToShow.push(usefulOrderInfo)
    }
    // console.log(res.data.data.value)
    return appointOrderToShow
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function (options) {
    // console.log(options)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:async function (option) {
    deliverOrderPage = 1
  appointOrderPage = 1
    if(!app.globalData.userInfo)
    {
      Dialog.alert({
        message: '请您先登录',
      }).then(() => {
        wx.switchTab({
          url: '../../pages/mine/index',
        })
      });
    }
    // console.log(option)
    else{

      let deliverOrderToShow =await this.getDeliverorder()
      let appointOrderToShow= await this.getAllAppointOrder()
      this.setData({
        active:app.globalData.orderPageActive,
        deliverOrderToShow,
        appointOrderToShow
      })
    }


    let res = await requests.storeInterface(null,null,null,null,null,null,null,app.globalData.openid,'getByUserId')
    console.log('商城订单',res.data.data.value)
    this.setData({
      shoppingOrderToShow:res.data.data.value
    })

    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
      var that =this
      // console.log('触底')
      //提示加载中
      const active = that.data.active

      if(active==0||active==1)
      {
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
        });
          tool.debounce(async ()=> {
            //结果： 延迟函数执行，不管触发多少次都只执行最后一次。
            if(active==0)
            {
              deliverOrderPage++
              let deliverOrderToShow =await that.getDeliverorder()
              if(deliverOrderToShow.length!=0)
              {
              // console.log('原数组',that.data.deliverOrderToShow)
              that.setData({
                deliverOrderToShow:[...that.data.deliverOrderToShow,...deliverOrderToShow]
              })
              }
              else
              {
                //提示没有更多了
                Toast.fail('没有更多~');
              }
            }
            else if(active ==1)
            {
            appointOrderPage++
            let appointOrderToShow =await that.getAllAppointOrder()
            if(appointOrderToShow.length!=0)
            {
            // console.log('原数组',that.data.deliverOrderToShow)
            that.setData({
              appointOrderToShow:[...that.data.appointOrderToShow,...appointOrderToShow]
            })
            }
            else
            {
              //提示没有更多了
              Toast.fail('没有更多~');
            }
            }
        },1000)()
      }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (opt) {
      // console.log(opt)
      let shareObj = {
        title:"分享订单",
        path:'/components/orderCard/orderCard'
      }
      return shareObj
  }
})